package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.serve.task.vo.IotMsgNotifyData;
import com.zzyl.serve.task.vo.IotMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author koi
 * @date 2025-05-11
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量保存设备数据信息
     * @param data
     */
    @Autowired
    private IDeviceDataService deviceDataService;
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData data) {
        //1.查询设备
        String  iotId = data.getHeader().getDeviceId();
        DeviceData device = deviceDataService.getOne(
                new LambdaQueryWrapper<DeviceData>()
                .eq(DeviceData::getIotId, iotId)
        );
        //判断是否为空，如果设备查不到，直接抛出异常终止运行
        if (device == null){
            throw new RuntimeException("设备不存在");
        }
        //2.构建设备数据
        List<IotMsgService> services = data.getBody().getServices();
        //遍历services，构建DeviceData
        services.forEach(service ->{
            //取出properties
            Map<String, Object> properties = service.getProperties();
            //单独处理上报日期时间
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            eventTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            LocalDateTime finalEventTime = eventTime;

            //转入多个设备数据
            List<DeviceData> list = new ArrayList<>();
            properties.forEach((key, value) -> {
                //构造者模式创建对象
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .functionId(key)
                        .dataValue(value.toString())
                        .alarmTime(finalEventTime)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .accessLocation(device.getBindingLocation())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .build();
                list.add(deviceData);
            });
            //3.批量保存
            saveBatch(list);

            //hash 结构来进行存储  大key  小key(设备id)  value(最新值)
            redisTemplate.opsForHash().put(RedisKeyConstants.IOT_DEVICE_LAST_DATA,iotId, list);

        });


    }
}
